package com.qxzn.app.api.api;

import android.app.DownloadManager;
import android.content.Context;
import android.content.IntentFilter;
import android.net.Uri;
import android.text.TextUtils;

import com.qxzn.app.api.util.DownloadBroadcast;
import com.qxzn.app.api.util.EventBusManager;
import com.qxzn.app.bean.EventBusBean;
import com.qxzn.app.util.AppUtil;
import com.qxzn.app.util.Constant;

import org.json.JSONObject;

import java.io.File;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class HttpRequest<T> {

    public static String AUTHORIZE_KEY = "";
    private static ApiService service;

    public static final String WS = "ws://14.29.144.175:8183/";
    //黄山服务器
//    public static String BASE_URL_AIUI = "http://10.10.12.109:8090/";
//    public static String BASE_URL_AIUI = "http://172.21.253.11:8090/";// TODO: 2019/4/22 发布版要改IP为：127.0.0.1:8090
    public static String BASE_URL_AIUI = "http://127.0.0.1:8090/";
    //    public static String BASE_URL_AIUI = "http://10.10.9.44:8090/";
    //生产服务器
//    public static String BASE_URL = "http://14.29.144.175:8090/";
    public static String BASE_URL = "https://qxzniot.com:8091/";
    //刘虹序服务器

    private static ApiService aiuiService;

    private HttpRequest() {

    }

    static {
        OkHttpClient client = new OkHttpClient.Builder()//okhttp设置部分，此处还可再设置网络参数
                .addInterceptor(new HttpLoggingInterceptor(message -> {
                    //打印retrofit日志
                    AppUtil.showLog("HTTP请求：" + message);
                }).setLevel(HttpLoggingInterceptor.Level.BODY))
                .addInterceptor(chain -> {
                    Request request = chain.request().newBuilder()
                            .header("Authorization", AUTHORIZE_KEY)
                            .build();
                    Response response = chain.proceed(request);
                    if (response != null) {
                        String json = response.peekBody(Long.MAX_VALUE).string();
                        if (json != null) {
                            try {
                                JSONObject jsonObject = new JSONObject(json);
                                if ("appkey验证有误".equals(jsonObject.optString("msg"))) {// TODO: 2019/5/27 暂时，等接口返回修改后再修改
                                    EventBusManager.post(new EventBusBean.Builder().id(Constant.EventBusId.ERROR_KEY).build());
//                                    request = chain.request().newBuilder()
//                                            .header("Authorization", AUTHORIZE_KEY)
//                                            .build();
//                                    response = chain.proceed(request);
//                                    RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), "{\"username\":\"" + "hsq1" + "\",\"userpwd\":\"" + "1" + "\"}");
//                                    Call<KeyBean> call = HttpRequest.getService().getKey(body);
//                                    KeyBean keyBean = call.execute().body();
//                                    if (keyBean != null && keyBean.getData() != null) {
//                                        HttpRequest.AUTHORIZE_KEY = keyBean.getData().getAppkey() + "-" + keyBean.getData().getInfokey();
//                                        request = chain.request().newBuilder()
//                                                .header("Authorization", AUTHORIZE_KEY)
//                                                .build();
//                                        response = chain.proceed(request);
//                                        AppUtil.showLog("key：" + HttpRequest.AUTHORIZE_KEY);
//                                    }
                                }
                            } catch (Exception e) {
                                AppUtil.showLog("异常：" + e);
                            }
                        }
                    }
                    return response;
                })
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        service = retrofit.create(ApiService.class);
    }

    public static ApiService getService() {
        AppUtil.showLog("Authorization：" + AUTHORIZE_KEY);
        return service;
    }

    public static ApiService getAIUIService() {
        OkHttpClient client = new OkHttpClient.Builder()//okhttp设置部分，此处还可再设置网络参数
                .addInterceptor(new HttpLoggingInterceptor(message -> {
                    //打印retrofit日志
                    AppUtil.showLog("AIUI-HTTP请求：" + message);
                }).setLevel(HttpLoggingInterceptor.Level.BODY))
                .addInterceptor(chain -> {
                    Request authorised = chain.request().newBuilder()
                            .header("Authorization", AUTHORIZE_KEY)
                            .build();
                    return chain.proceed(authorised);
                })
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL_AIUI)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        aiuiService = retrofit.create(ApiService.class);
        return aiuiService;
    }

    private static Request request(Interceptor.Chain chain) {
        return chain.request().newBuilder()
                .header("Authorization", AUTHORIZE_KEY)
                .build();
    }

    public static RequestBody getDefaultBody(com.alibaba.fastjson.JSONObject params) {
        return RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), com.alibaba.fastjson.JSON.toJSONString(params));
    }

    public static RequestBody getPartBody(String param) {
        if (TextUtils.isEmpty(param)) {
            return null;
        }
        return RequestBody.create(MediaType.parse("multipart/form-data"), param);
    }

    public static MultipartBody.Part getPartFileBody(File file) {
        return getPartFileBody(file, "file");
    }

    public static MultipartBody.Part getPartFileBody(File file, String key) {
        if (file == null) {
            return null;
        }
        RequestBody requestFile = RequestBody.create(MediaType.parse("application/otcet-stream"), file);
        return MultipartBody.Part.createFormData(key, file.getName(), requestFile);
    }

    public static void downloadFile(Context context, String title, String url, String directory, String fileName, DownloadBroadcast mDownloadBroadcast) {
        AppUtil.showLog(url);
        //文件下载链接
//        String url = "https://imtt.dd.qq.com/16891/F6033A925A78455922CBD51D52BFFB4F.apk?fsname=com.miniapp.jsq_1.2.7_7.apk";
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        // 通知栏的下载通知
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        if (!TextUtils.isEmpty(title)) {
            request.setTitle(title);
        }
//        request.setMimeType("application/vnd.android.package-archive");
        request.setDestinationInExternalFilesDir(context, directory, fileName);
        long downloadId = downloadManager.enqueue(request);
        AppUtil.showLog("downloadId：" + downloadId);
        //文件下载完成会发送完成广播，可注册广播进行监听
        if (mDownloadBroadcast != null) {
            IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
            intentFilter.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);
            intentFilter.addAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
            context.registerReceiver(mDownloadBroadcast, intentFilter);
        }
    }

}
